import os
import sys
import argparse
import logging
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC
from mutagen.flac import FLAC
from mutagen.wave import WAVE
from datetime import datetime

def setup_logger(log_path=None):
    """配置并返回日志记录器"""
    logger = logging.getLogger('cover_remover')
    logger.setLevel(logging.INFO)

    # 设置日志格式
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    # 文件处理器（如果提供了路径）
    if log_path:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = os.path.join(log_path, f"cover_removal_{timestamp}.log")
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    return logger

def remove_mp3_cover(logger, file_path):
    """移除MP3文件封面"""
    try:
        audio = MP3(file_path, ID3=ID3)
        if 'APIC:' in audio.tags:
            audio.tags.delall('APIC:')
            audio.save()
            logger.info(f"成功移除封面: {file_path}")
            return True
        else:
            logger.info(f"文件无封面: {file_path}")
            return False
    except Exception as e:
        logger.error(f"处理文件 {file_path} 时出错: {str(e)}")
        return False

def remove_flac_cover(logger, file_path):
    """移除FLAC文件封面"""
    try:
        audio = FLAC(file_path)
        if audio.pictures:
            audio.clear_pictures()
            audio.save()
            logger.info(f"成功移除封面: {file_path}")
            return True
        else:
            logger.info(f"文件无封面: {file_path}")
            return False
    except Exception as e:
        logger.error(f"处理文件 {file_path} 时出错: {str(e)}")
        return False

def remove_wav_cover(logger, file_path):
    """移除WAV文件封面"""
    try:
        audio = WAVE(file_path)
        if audio.tags and 'APIC:' in audio.tags:
            audio.tags.delall('APIC:')
            audio.save()
            logger.info(f"成功移除封面: {file_path}")
            return True
        else:
            logger.info(f"文件无封面: {file_path}")
            return False
    except Exception as e:
        logger.error(f"处理文件 {file_path} 时出错: {str(e)}")
        return False

def main():
    # 命令行参数解析
    parser = argparse.ArgumentParser(description='批量移除音乐文件封面')
    parser.add_argument('path', help='音乐文件夹路径')
    parser.add_argument('--log-dir', default=None,
                        help='日志保存目录（可选，默认为 ~/cover_removal_logs）')
    args = parser.parse_args()

    music_path = args.path

    # 验证输入路径是否存在
    if not os.path.exists(music_path):
        print(f"错误: 路径不存在: {music_path}")
        sys.exit(1)

    if not os.path.isdir(music_path):
        print(f"错误: 需要文件夹路径，但提供的似乎是文件: {music_path}")
        sys.exit(1)

    # 配置日志
    if args.log_dir:
        log_dir = args.log_dir
    else:
        log_dir = os.path.join(os.path.expanduser('~'), "cover_removal_logs")

    os.makedirs(log_dir, exist_ok=True)

    logger = setup_logger(log_dir)
    logger.info("="*50)
    logger.info(f"开始处理音乐目录: {music_path}")
    logger.info(f"日志保存在: {log_dir}")
    logger.info("="*50)

    # 处理统计
    total_files = 0
    processed_files = 0
    removed_covers = 0
    errors = 0

    # 遍历目录处理文件
    for root, _, files in os.walk(music_path):
        for file in files:
            total_files += 1
            file_path = os.path.join(root, file)

            try:
                if file.lower().endswith(".mp3"):
                    if remove_mp3_cover(logger, file_path):
                        removed_covers += 1
                    processed_files += 1

                elif file.lower().endswith(".flac"):
                    if remove_flac_cover(logger, file_path):
                        removed_covers += 1
                    processed_files += 1

                elif file.lower().endswith(".wav"):
                    if remove_wav_cover(logger, file_path):
                        removed_covers += 1
                    processed_files += 1

                else:
                    logger.info(f"跳过不支持的文件格式: {file_path}")

            except Exception as e:
                errors += 1
                logger.error(f"处理文件 {file_path} 时发生意外错误: {str(e)}")

    # 生成最终报告
    logger.info("="*50)
    logger.info(f"处理完成！统计信息:")
    logger.info(f"扫描文件总数: {total_files}")
    logger.info(f"处理文件数量: {processed_files}")
    logger.info(f"移除封面数量: {removed_covers}")
    logger.info(f"错误数量: {errors}")

    if total_files == 0:
        logger.warning("警告: 未找到任何文件，请检查路径是否正确！")

    logger.info("="*50)

if __name__ == "__main__":
    main()